package com.cloudptt.wp.ui.group.add;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.Common;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.call.group.fsm.IRollback;
import com.cloudptt.api.product.func.call.group.fsm.RollbackTimer;
import com.cloudptt.api.product.func.message.NotifyNewGroupListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.AddrOperator;
import com.cloudptt.api.product.operator.SysMsgOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.BaseActivity;
import com.cloudptt.wp.ui.dlg.UiDlg;
import com.cloudptt.wp.ui.group.add.adapt.UserSelectAdapter;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class NewGroupActivity extends BaseActivity implements  OnClickListener,CallBack,NotifyNewGroupListener,IRollback{
	private static final String TAG = "NewGroupActivity";
	private Product product = null;
	private ListView mListView;
	private Button okBtn = null;
	private UserSelectAdapter adapt = null;
	private List<UserInfo> list = null;
	private McIdInfo info = null;
	private Dialog progressDialog = null;
	private RollbackTimer rollbackTimer = null;
	private String curMcId = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(getResources().getColor(R.color.actionbar_bg));
		super.onCreate(savedInstanceState);
		getActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.app_theme_color_primary));
		getActionBar().hide();

		setContentView(R.layout.activity_new_group);
		initView();
		initData();
		initNotificationLayout();
	}

	private void initView(){
		//ActionBar
		ImageView iv = (ImageView) findViewById(R.id.back_up_icon);
		iv.setOnClickListener(this);
		TextView tv = (TextView) findViewById(R.id.titleTv);
		tv.setText(R.string.new_group);

		okBtn = (Button)findViewById(R.id.ok_btn);
		okBtn.setOnClickListener(this);

		mListView = (ListView)findViewById(R.id.device_list);
		mListView.setVerticalScrollBarEnabled(false);
	}

	private void initData()
	{
		SysApplication app = ((SysApplication) getApplicationContext());
		product = app.getProduct();

		if(product!=null)
		{
			product.setNewGroupListener(this);
			AddrOperator operator = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
			if(product.getMcpttLoginInfo() != null
					&& product.getMcpttLoginInfo().getMcIdInfo() != null
					&& product.getMcpttLoginInfo().getMcIdInfo().getAddrId() != null)
			{
				curMcId = product.getMcpttLoginInfo().getMcIdInfo().getAddrId();
			}
			
			list = operator.getNewAddressList(GroupInfo.Group_Num_All,curMcId);
			info = product.getMcpttLoginInfo().getMcIdInfo();
			adapt = new UserSelectAdapter(NewGroupActivity.this,list,info,this);
			mListView.setAdapter(adapt);
		}
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}

		if(product!=null)
		{
			product.setNewGroupListener(null);
		}
	}
	@Override
	protected void onDestroy() {
		Log.d(TAG, "DeviceManagerActivity onDestroy");
		if(rollbackTimer != null)
		{
			rollbackTimer.cancelTimer();
			rollbackTimer = null;
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		if(id == R.id.back_up_icon){
			ScreenManager.getScreenManager().popActivity();

		}
		else if(id == R.id.ok_btn){
			doReportToSvr();
		}
	}

	private void doReportToSvr()
	{
		if(adapt != null
				&& adapt.getResult() != null)
		{
			Set<String> result = adapt.getResult();
			Log.d(TAG, "doReportToSvr result = " + result);
			if(result == null
					|| result.size() <= 0)
			{
				CommDlg.show(NewGroupActivity.this, NewGroupActivity.this.getResources().getString(R.string.group_memeber_null));
				return;
			}
			if(result.size() == list.size())
			{
				CommDlg.show(NewGroupActivity.this, NewGroupActivity.this.getResources().getString(R.string.group_exist));
				return;
			}


			SysApplication app = ((SysApplication) getApplicationContext());
			Product product = app.getProduct();
			if(product == null){
				return;
			}
			SysMsgOperator op = (SysMsgOperator)product.getOperator(ProductConst.Func_SysMsg);
			StringBuffer strBuf = new StringBuffer(curMcId);
			for(Iterator<String> itor = result.iterator();itor.hasNext();)
			{
				String mcId = itor.next();
				strBuf.append("|").append(mcId);
			}
			op.sendSelfOrganizingGroupMsg(Common.getDateAndTime_s(),strBuf.toString());
			this.rollbackTimer = new RollbackTimer(NewGroupActivity.this,3,this);
		}
	}

	@Override
	public void hasCheck(boolean isCheck) {
		// TODO Auto-generated method stub
		Log.d(TAG, "doReportToSvr isCheck = " + isCheck);
		if(isCheck)
		{
			okBtn.setVisibility(View.VISIBLE);
			okBtn.setText(R.string.ok);
			if(adapt != null
					&& adapt.getResult() != null)
			{
				Set<String> set = adapt.getResult();
				if(set.size() > 0)
				{
					String str = this.getString(R.string.ok) + "(" + set.size() + ")";
					okBtn.setText(str);
				}
			}
		}
		else
		{
			okBtn.setVisibility(View.GONE);
		}
		
	}

	@Override
	public void newGroupResult(boolean result, String groupId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "newGroupResult result = " + result + " groupId = " + groupId);
		if(rollbackTimer != null)
		{
			rollbackTimer.cancelTimer();
			rollbackTimer = null;
		}

		showWaitCover(false);

		String str = NewGroupActivity.this.getResources().getString(R.string.new_group_result_1);
		StringBuffer strBuf = new StringBuffer(str);
		if(result)
		{
			str = NewGroupActivity.this.getResources().getString(R.string.success);
			strBuf.append(str);
			str = NewGroupActivity.this.getResources().getString(R.string.new_group_result_2);
			strBuf.append(str);
			strBuf.append(groupId);

			setDefaultGroup(groupId);

			ScreenManager.getScreenManager().popActivity();
		}
		else
		{
			str = NewGroupActivity.this.getResources().getString(R.string.fail);
			strBuf.append(str);
		}
		CommDlg.show(NewGroupActivity.this, strBuf.toString());
	}

	private void setDefaultGroup(String groupId)
	{
		Log.d(TAG, "setCurGroup groupId = " + groupId);
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}
		Log.d(TAG, "setCurGroup product = " + product);
		if(product!=null)
		{
			product.setCurGroupId(groupId);
		}
	}

	private void showWaitCover(final boolean show) 
	{
		if (show) 
		{
			progressDialog = UiDlg.createLoadingDialog(NewGroupActivity.this, 
					getString(R.string.please_wait));
			progressDialog.show();
		} 
		else 
		{
			if(progressDialog != null)
			{
				progressDialog.dismiss();
			}
		}
	}

	@Override
	public void rollback() {
		// TODO Auto-generated method stub
		newGroupResult(false,"timeout");
	}
}
